﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YmtSystem.CrossCutting;
using YmtAuth.Common;
using YmtAuth.Common.Utility;
using YmtAuth.Domain.Model.User;
using YmtAuth.Domain.Shard;

namespace YmtAuth.Domain.Model.LoginCredential
{
    /// <summary>
    /// 用户登录凭据
    /// </summary>
    public class UserLoginCredential : Entity
    {
        /// <summary>
        /// 空凭据
        /// </summary>
        public static readonly UserLoginCredential EmptyUserLoginCredential = new UserLoginCredential { _id = string.Empty, Value = -1 };
        /// <summary>
        /// 凭据Key 
        /// </summary>
        public override object _id { get;protected set; }
        /// <summary>
        /// 凭据Value
        /// </summary>
        public int Value { get; set; }

        /// <summary>
        /// 创建用户凭据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        [Obsolete("使用Create(Dictionary<string, object> uData)", false)]
        public static UserLoginCredential Create(string key, string password, Dictionary<string, object> uData)
        {
            YmtAuthAssert.AssertIsNotNull(() => string.IsNullOrEmpty(key));
            YmtAuthAssert.AssertIsNotNull(() => (int)uData.TryGetV(YmtUserKey.uId, -1) == -1);
            var credential = GenerateCredential(key, password);
            YmatouLoggingService.Debug("key->{0},uid->{1},new key->{2}", key, uData.TryGetV(YmtUserKey.uId), credential);
            return new UserLoginCredential { _id = credential, Value = (int)uData.TryGetV(YmtUserKey.uId, -1) };
        }

        /// <summary>
        /// 根据uData数据容器生成UserLoginCredential实例
        /// </summary>
        /// <param name="uData"></param>
        /// <returns></returns>
        public static UserLoginCredential Create(Dictionary<string, object> uData)
        {
            if (uData == null || uData.Count == 0) return EmptyUserLoginCredential;
            var uid = Convert.ToInt32(uData.TryGetV(YmtUserKey.uId, YmtUserKey.uId_Inval));
            var ukey = uData.TryGetV(YmtUserKey.rloginKey, YmtUserKey.rloginKey_Invalid);
            var pas = uData.TryGetV(YmtUserKey.sPassword, YmtUserKey.sPassword_Inval);
            if (string.IsNullOrEmpty(ukey.ToString()) && string.IsNullOrEmpty(pas.ToString()) || string.IsNullOrEmpty(ukey.ToString()))
                return EmptyUserLoginCredential;
            var rtype = uData.TryGetV(YmtUserKey.rType, YmtUserKey.rType_def_Val);
            YmatouLoggingService.Debug("rType->{0},loginKey->{1}", rtype, ukey);
            //var credential = GenerateCredential(ukey.ToString(), pas.ToString());
            var credential = ImportDataLoginKey(ukey.ToString(), pas.ToString());
            return new UserLoginCredential { _id = credential, Value = uid };
        }

        /// <summary>
        /// 生成登录认证凭据,
        /// </summary>     
        /// <returns></returns>
        public static string GenerateCredential(string key, string password)
        {
            YmtAuthAssert.AssertIsNotNull(() => string.IsNullOrEmpty(key));
            //兼容老的业务
            var encrypt = new Encrypt();
            var encryptPassword = encrypt.Md5Encrypt(encrypt.AesEncrypt(password, true));
            //新的key
            var newId = CryptoUtil.Md5Encrypt(string.Format("{0}&{1}", key.ToLower(), encryptPassword));
            //var newId = CryptoUtil.Md5Encrypt(string.Format("{0}&{1}", key, password));
            return newId;
        }

        /// <summary>
        /// 数据导入生成key
        /// </summary>
        /// <param name="key"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string ImportDataLoginKey(string key, string password)
        {
            YmtAuthAssert.AssertIsNotNull(() => string.IsNullOrEmpty(key));
            return CryptoUtil.Md5Encrypt(string.Format("{0}&{1}", key.ToLower(), password));
        }

        public static string GetUserLoginKey(Dictionary<string, object> uData)
        {
            return uData.TryGetV(YmtUserKey.rloginKey, YmtUserKey.rloginKey_Invalid).ToString();
        }

        /// <summary>
        /// 认证
        /// </summary>
        /// <param name="userKey"></param>
        /// <returns></returns>
        public ModelExecuteResult<YmtUser> Auth(string userKey = "")
        {
            if (string.IsNullOrEmpty(_id.ToString()))
            {
                YmtSystem.CrossCutting.YmatouLoggingService.Error("凭据 {0} 无效", userKey);
                return new ModelExecuteResult<YmtUser>(false, string.Format("凭据 {0} 无效", userKey), YmtUser.Empty);
            }
            return new ModelExecuteResult<YmtUser>(true, "ok", YmtUser.Create(this.Value)); ;
        }

        public override string ToString()
        {
            return string.Format("{0}\"_id\":\"{1}\",\"Value\":\"{2}\"{3}", "{", _id, Value, "}");
        }

        protected override IEnumerable<object> CompareValues()
        {
            yield return this._id;
            yield return this.Value;
        }
    }
}
